package main

import (
	"fmt"
	"go_study/retriever/mock"
	"go_study/retriever/real"
	"time"
)

type Retriever interface {
	Get(url string) string
}

type Poster interface {
	Post(url string, form map[string]string) string
}

const url = "http://www.baidu.com"

func download(r Retriever) string {
	return r.Get(url)
}

func post(p Poster) {
	p.Post(url, map[string]string{
		"name":    "thank",
		"address": "Beijing",
	})
}

// 组合
type RetrieverPoster interface {
	Retriever
	Poster
}

func session(rp RetrieverPoster) string {
	rp.Post(url, map[string]string{"contents": "another faked baidu.com"})
	return rp.Get(url)
}

func main() {
	var r Retriever
	mockRetriever := mock.Retriever{Contents: "this is fake baidu.com"}
	r = &mockRetriever
	inspect(r)

	r = &real.Retriever{
		UserAgent: "Mozilla/5.0",
		TimeOut:   time.Minute,
	}
	//fmt.Println(download(r))
	inspect(r)

	// Type assertion: 类型断言
	if mockRetriever, ok := r.(*mock.Retriever); ok {
		fmt.Println(mockRetriever.Contents)
	} else {
		fmt.Println("r is not mock Retriever")
	}

	fmt.Println("Try a session with mockRetriever")
	fmt.Println(session(&mockRetriever))
}

func inspect(r Retriever) {
	fmt.Println("Inspecting: ", r) // 这里如果是mockRetriever是被重写: 系统string
	// interface变量r: 不是一个简单类型, 它肚子里有一个类型, 还有一个值
	fmt.Printf(" > Type: %T,  Value: %v\n", r, r)
	fmt.Print(" > Type switch: ")
	switch v := r.(type) {
	case *mock.Retriever:
		fmt.Println("Contents: ", v.Contents)
	case *real.Retriever:
		fmt.Println("UserAgent: ", v.UserAgent)
	}
	fmt.Println()
}
